package com.lishide.scrollrecyclerview;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.wifi.WifiConfiguration;
import android.net.wifi.WifiManager;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.animation.GlideAnimation;
import com.bumptech.glide.request.target.SimpleTarget;
import com.google.gson.Gson;
import com.lishide.scrollrecyclerview.coreokhttp.parser.impl.StringParser;
import com.lishide.scrollrecyclerview.json.JSONParser;
import com.lishide.scrollrecyclerview.utils.NetUtil2;
import com.lishide.scrollrecyclerview.utils.WiFiUtils;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.Map;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

/**
 * Created by zhaoyf on 2018/9/13.
 */

public class MainActivity extends Activity{

    private final String TAG="zhao";
    private String SERVICE_URL;
    private ImageView zhiboImage,dianboImage,toupinImage;
    private TextView wifiAPName,wifiApPwd;
    private TextView weatherText;
    private TextView boxIdTextView;
    private WifiManager mWifiManager;
    private WifiApManager wifiApManager;
    private WifiConfiguration wifiConfiguration;
    public static final int WIFI_AP_STATE_ENABLED = 13;
    private BoxInfo boxInfo;
    private FrameLayout main_layout;
    private SharedPreferences sharedPreferences;
    private WiFiUtils wiFiUtils;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main_layout);
        initView();
        registNetReceiver();

    }

    private void registNetReceiver() {
        IntentFilter filter=new IntentFilter();
        filter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
        registerReceiver(netChangeReceiver,filter);
    }

    BroadcastReceiver netChangeReceiver=new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            if (intent.getAction().equals(ConnectivityManager.CONNECTIVITY_ACTION)){
                if (NetUtil2.isNetworkAvailable(context)){
                    if (NetUtil2.isEthernetConnect(context)){
                        //开启热点
                        updateWifiApInfo();
                    }else {
                        wifiAPName.setText("WIFI已连接");
                        wifiApPwd.setText("");
                    }
                }else {
                    wifiAPName.setText("网络未连接");
                    wifiApPwd.setText("");
                    closeApAndOpenWifi();
                }
                if (isNetworkAvailable()){
                    getDataFromService();
//                    getWether();
                }else {
                    handler.sendEmptyMessage(2);
                }
            }

        }
    };

    private void closeApAndOpenWifi() {
        int state = wiFiUtils.getWifiAPState();

        if(state==13|| state==11){
            wiFiUtils.closeWifiAp();
        }

        if(!NetUtil2.isWifiConnect(this)) {
            boolean ws = wiFiUtils.setWifiEnabled(this);
            if (ws && NetUtil2.isWifiConnect(this)) {

//                Message msg = new Message();
//                Bundle b = new Bundle();// 存放数据
//                b.putString("ssid", "WIFI已连接");
//                b.putString("password", "");
//                msg.setData(b);
//                msg.what = 6;
            }
        }else{
//            Message msg = new Message();
//            Bundle b = new Bundle();// 存放数据
//            b.putString("ssid", "WIFI已连接");
//            b.putString("password", "");
//            msg.setData(b);
//            msg.what = 6;
        }
    }

    private Handler handler=new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what){
                case 0:
                    Bundle bundle = msg.getData();
                    String temp = bundle.getString("temp");
                    String weather = bundle.getString("weather");
                    weatherText.setText(weather+"   "+temp);
                    break;

                case 1:
                    Bundle bundle2=msg.getData();
                    String url=bundle2.getString("url");
                    String boxId=bundle2.getString("boxId");
                    if (null!=url&&!url.equals("")){
                        setMainBg(url);
                    }
                    boxIdTextView.setText(boxId);

                    break;

                case 2:
                    String imageUrl=sharedPreferences.getString("url","");
                    String boxId2=sharedPreferences.getString("boxId","");
                    if (!imageUrl.equals("")){
                        setMainBg(imageUrl);
                    }
                    boxIdTextView.setText(boxId2);

                    break;
            }
        }
    };

    public void updateWifiApInfo(){


        wifiApManager=new WifiApManager(this);
        wifiConfiguration=wifiApManager.getWifiApConfiguration();
        boolean wifiEnable=mWifiManager.isWifiEnabled();

        if(null!=wifiConfiguration){
            String wifiApSSIDString=String.format(wifiConfiguration.SSID);
            String wifiAPPwdString=String.format(wifiConfiguration.preSharedKey);
            wifiAPName.setText("wifi账号："+wifiApSSIDString);
            wifiApPwd.setText("wifi密码："+wifiAPPwdString);
        }else {
//            wifiConfiguration=new WifiConfiguration();
//            wifiConfiguration.SSID=WIFI_AP_SSID;
//            wifiConfiguration.preSharedKey=WIFI_AP_PWD;
//            wifiConfiguration.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_PSK);
            wifiAPName.setText("");
            wifiApPwd.setText("");
        }

        if (wifiApManager.getWifiApState()!=WIFI_AP_STATE_ENABLED){
            boolean wifiConfigAble= wifiApManager.setWifiApConfiguration(wifiConfiguration);
            boolean wifihotEnable=wifiApManager.setWifiApEnabled(wifiConfiguration,true);
			Log.d(TAG,"wifi热点设置：SSID="+wifiConfiguration.SSID+"密码="+wifiConfiguration.preSharedKey);
			Log.d(TAG,"wifi热点设置"+wifiConfigAble);
			Log.d(TAG,"wifi热点打开"+wifihotEnable);
        }

    }

    @Override
    protected void onStart() {
        super.onStart();
        if (NetUtil2.isEthernetConnect(this)){
            updateWifiApInfo();
        }
    }

    private void initView() {
        wiFiUtils=WiFiUtils.getInstance(this);
        mWifiManager = (WifiManager)getApplicationContext().getSystemService(Context.WIFI_SERVICE);
//        SERVICE_URL="http://gw.dtlx.ltd/box/info?macAddress=" + getMacAddress();
        SERVICE_URL="http://gw.dtlx.ltd/box/info?macAddress=";
        sharedPreferences=getSharedPreferences("ider",MODE_PRIVATE);
        main_layout=(FrameLayout)findViewById(R.id.main_bg);
        boxIdTextView=(TextView)findViewById(R.id.boxid);
        zhiboImage=(ImageView) findViewById(R.id.zhibo_iv);
        dianboImage=(ImageView)findViewById(R.id.dianbo_iv);
        toupinImage=(ImageView)findViewById(R.id.toupin_iv);
        zhiboImage.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                launchApp(new ComponentName("com.qclive.tv","com.qclive.tv.MainActivity"));
            }
        });
        dianboImage.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                launchApp("com.yidian.calendar");
            }
        });
        toupinImage.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                launchApp("com.hpplay.happyplay.aw");
            }
        });

        wifiAPName=(TextView)findViewById(R.id.wifi_ap_name);
        wifiApPwd=(TextView)findViewById(R.id.wifi_ap_pwd);
        weatherText=(TextView)findViewById(R.id.weather);

        if (isNetworkAvailable()){
//            getDataFromService();
//            getWether();
        }else {
            wifiAPName.setText("网络未连接");
            handler.sendEmptyMessage(2);
        }




    }



    private void getDataFromService() {
        Log.d(TAG,"getDataFromService URL ="+SERVICE_URL);
        sendOKHttpRequest(SERVICE_URL, new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Log.d(TAG,"getDataFromService onFailure = "+e.toString());
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String jsonString = response.body().string();
                Log.d(TAG,"getDataFromService json = "+jsonString);
                if (!TextUtils.isEmpty(jsonString)){
                    boxInfo=new Gson().fromJson(jsonString,BoxInfo.class);
                    Log.d(TAG,boxInfo.toString());

                    if (boxInfo.getState()==1){
                        String url=boxInfo.getLogo();
                        String boxId=boxInfo.getId()+"";
                        Log.d(TAG," getDataFromService state==1 url ="+url);

                        if (!url.equals("")){
                            sharedPreferences.edit().putString("url",url).commit();
                            sharedPreferences.edit().putString("boxId",boxId).commit();
                            Message msg = new Message();
                            Bundle b = new Bundle();// 存放数据
                            b.putString("url", url);
                            b.putString("boxId", boxId);
                            msg.setData(b);
                            msg.what=1;
                            handler.sendMessage(msg);
                        }


                    }else {
                        Log.d(TAG,"getDataFromService state !=1");
                        handler.sendEmptyMessage(2);
                    }
                }
            }
        });
    }

    public void getWether() {
        OkHttpClient okHttpClient = new OkHttpClient();
        StringParser parser = new StringParser();
        String weatherUrl = "http://jisutqybmf.market.alicloudapi.com/weather/query?city=%E8%A5%BF%E5%AE%89";
        Request request = new Request.Builder().url(weatherUrl).addHeader("Authorization", "APPCODE 52e6c01a15eb4302b71e9225643e1cf0").build();
        okHttpClient.newCall(request).enqueue(new com.lishide.scrollrecyclerview.coreokhttp.parser.Callback<String>(parser) {
            @Override
            public void onResponse(Object t) {
                try {
                    Log.d(TAG, "getWether onResponse: " + t.toString());
                    if (t != null) {
                        Map data = JSONParser.StringToJSONObjectParser(t.toString());
                        if (data.containsKey("result")) {
                            Map result = (Map) data.get("result");

                            String weather=result.get("weather").toString();
                            String temp=result.get("temp").toString();
                            String temphigh=result.get("temphigh").toString();

                            Message msg = new Message();
                            Bundle b = new Bundle();// 存放数据
                            b.putString("weather", weather);
                            b.putString("temp", temp);
                            b.putString("temphigh", temphigh);

                            msg.setData(b);
                            msg.what = 0;
                            handler.sendMessage(msg); // 向Handler发送消息,更新UI
                            Log.d(TAG, "getWether: " + weather + temp+"℃");
                        }
                    }else {
                        Log.d(TAG,"getWeather onResponse : t="+t);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    Log.d(TAG,"getWeather :"+e.toString());
                }
            }

            @Override
            public void onFailure(IOException e) {
                super.onFailure(e);
                Log.d(TAG,"getWeather ="+e.toString());
            }
        });
    }


    public void launchApp(String pkgName) {
        try {
            Intent intent = getPackageManager()
                    .getLaunchIntentForPackage(pkgName);
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK
                    | Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED
                    | Intent.FLAG_ACTIVITY_CLEAR_TOP);
            startActivity(intent);
        } catch (Exception e) {
            e.printStackTrace();
            Toast.makeText(this,"应用未安装",Toast.LENGTH_SHORT).show();
        }
    }

    public void launchApp(ComponentName componentName) {
        Intent intent = new Intent();
        intent.setComponent(componentName);
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK
                | Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED
                | Intent.FLAG_ACTIVITY_CLEAR_TOP);

        try {
            startActivity(intent);
        } catch (Exception e) {
            e.printStackTrace();
            Toast.makeText(this,"应用未安装",Toast.LENGTH_SHORT).show();
        }
    }




    public boolean isNetworkAvailable() {
        ConnectivityManager connectivity = (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);
        if (connectivity != null) {
            NetworkInfo info = connectivity.getActiveNetworkInfo();
            if (info != null && info.isConnected()) {
                // 当前网络是连接的
                if (info.getState() == NetworkInfo.State.CONNECTED) {
                    // 当前所连接的网络可用
                    return true;
                }
            }
        }
        return false;
    }

    private int menuCount;

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode== KeyEvent.KEYCODE_MENU){
            Log.d(TAG,"KEYCODE_MENU : "+keyCode);
            menuCount++;
            if (menuCount==5){
                menuCount=0;
                //com.android.settings/.Settings
                launchApp(new ComponentName("com.android.settings","com.android.settings.Settings"));
            }

            return true;
        }else {
            menuCount=0;
        }
        if (keyCode==KeyEvent.KEYCODE_BACK){
            return true;
        }

        return super.onKeyDown(keyCode, event);
    }

    public void sendOKHttpRequest(String address, okhttp3.Callback callback) {

        OkHttpClient okHttpClient = new OkHttpClient();
        Request request = new Request.Builder().url(address).build();
        okHttpClient.newCall(request).enqueue(callback);

    }

    private void setMainBg(String url){

        Glide.with(this)
                .load(url)
                .asBitmap()
//                .diskCacheStrategy(DiskCacheStrategy.NONE)
                .into(new SimpleTarget<Bitmap>(1920,1080) {
                    @Override
                    public void onResourceReady(Bitmap resource, GlideAnimation<? super Bitmap> glideAnimation) {
                        Drawable drawable = new BitmapDrawable(resource);
                        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
                            main_layout.setBackground(drawable);
                        }
                    }
                });
    }

    public static String getMacAddress() {
        try {
            return loadFileAsString("/sys/class/net/eth0/address")
                    .toUpperCase().substring(0, 17);
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }

    public static String loadFileAsString(String filePath) throws IOException {
        StringBuffer fileData = new StringBuffer(1000);
        BufferedReader reader = new BufferedReader(new FileReader(filePath));
        char[] buf = new char[1024];
        int numRead = 0;
        while ((numRead = reader.read(buf)) != -1) {
            String readData = String.valueOf(buf, 0, numRead);
            fileData.append(readData);
        }
        reader.close();
        return fileData.toString();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        try{
            unregisterReceiver(netChangeReceiver);
        }catch (Exception e){
            e.printStackTrace();
        }
    }
}
